package com.linkage.jz.bankruptcy.activity.Project;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.FileAdapter;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.ProNodeInfo;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.fragment.Project.ProFlowFragment;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.MapUtil;
import com.linkage.jz.bankruptcy.widget.CommonPopupMenu;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;
import com.linkage.seapeak.activity.user.ImageShowActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * 进度详情
 */
public class ProFlowDetailActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = ProFlowDetailActivity.class.getSimpleName();

    public static final String KEY_ID = "id";
    public static final String KEY_FLOW = "flow";

    private boolean canEdit = false;
    private boolean canDel = false;


    private String mProjectId;
    private String mId;
    private ProNodeInfo mProNode;
    private LinearLayout ll_addr;

    private CommonPopupMenu popupMenu;

    private RecyclerView mFileRecyclerView;
    private List<TaskAtta> mFileList = new ArrayList<>();
    private FileAdapter mFileAdapter;

    private TextView tv_flow_title, tv_flow_content, tv_flow_time, tv_flow_time_start, tv_flow_time_end, tv_flow_countdown, tv_flow_location;


    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
    }

    @Override
    public void initTitle() {
    }

    @Override
    public void initView() {
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_pro_flow_detail);
        super.onCreate(savedInstanceState);
        titlebar_title.setText("节点详情");
        EventBus.getDefault().register(this);

        mProjectId = getIntent().getStringExtra(KEY_PROJECTID);
        mId = getIntent().getStringExtra(KEY_ID);
        mProNode = (ProNodeInfo) getIntent().getSerializableExtra(KEY_FLOW);

        initViews();
        getDetail();
    }

    private Timer mTimer;

    @Override
    public void onResume() {
        super.onResume();
        LogUtil.i("ProFlowFragment", "-------->开启定时器");
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mProNode.isCountdown()) {
                            long gap = -1;
                            if (TextUtils.equals(mProNode.getTimeType().getValue(), "0")) {
                                gap = mProNode.getStartTime() - (System.currentTimeMillis() / 1000);
                            } else {
                                gap = mProNode.getEndTime() - (System.currentTimeMillis() / 1000);
                            }
                            tv_flow_countdown.setText(ProFlowFragment.formatTimeGap(gap));
                        }
                    }
                });
            }
        };
        mTimer = new Timer();
        mTimer.schedule(task, 1000, 1000);
    }

    @Override
    public void onPause() {
        super.onPause();
        LogUtil.i("ProFlowFragment", "-------->关闭定时器");
        mTimer.cancel();
        mTimer = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void initViews() {
        tv_flow_title = findViewById(R.id.tv_flow_title);
        tv_flow_content = findViewById(R.id.tv_flow_content);
        tv_flow_time = findViewById(R.id.tv_flow_time);
        tv_flow_time_start = findViewById(R.id.tv_flow_time_start);
        tv_flow_time_end = findViewById(R.id.tv_flow_time_end);
        tv_flow_countdown = findViewById(R.id.tv_flow_countdown);
        tv_flow_location = findViewById(R.id.tv_flow_location);
        ll_addr = findViewById(R.id.ll_addr);





        mFileRecyclerView = findViewById(R.id.recycler_files);
        mFileRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mFileAdapter = new FileAdapter(this, mFileList);
//        mFileAdapter.openLoadAnimation();
        mFileRecyclerView.setAdapter(mFileAdapter);
//        mFileAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                switch (view.getId()) {
//                    case R.id.tv_file_name:
//                        openOrDownloadFile(mFileList.get(position), ProFlowDetailActivity.this);
//                        break;
//                }
//            }
//        });

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btn_login:
                break;
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_FLOW)) {
            finish();
        }
    }

    private void refreshDetail() {
        tv_flow_title.setText(mProNode.getNodeName());
        tv_flow_content.setText(mProNode.getNodeNote());
        if (mProNode.getSysAddressInfo() != null) {
            tv_flow_location.setText(mProNode.getSysAddressInfo().getFullAddress());
            ll_addr.setVisibility(View.VISIBLE);
        } else {
            tv_flow_location.setText("");
            ll_addr.setVisibility(View.GONE);
        }

        tv_flow_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final List<String> values = new ArrayList<String>();

                AlertDialog.Builder builder = new AlertDialog.Builder(ProFlowDetailActivity.this);

                //builder.setIcon(R.drawable.ic_launcher);
                builder.setTitle("请选择");
                //    指定下拉列表的显示数据
                String[] strTypes = new String[]{};
                int num = 0;
                if(MapUtil.isBaiduMapInstalled())
                {
                    strTypes = Arrays.copyOf(strTypes, num+1);

                    strTypes[num]="百度地图";
                    num++;
                }
                if(MapUtil.isGdMapInstalled())
                {
                    strTypes = Arrays.copyOf(strTypes, num+1);

                    strTypes[num]="高德地图";
                    num++;
                }
                if(MapUtil.isTencentMapInstalled())
                {
                    strTypes = Arrays.copyOf(strTypes, num+1);

                    strTypes[num]="腾讯地图";
                    num++;
                }
                final String[] finalstrTypesp= strTypes;

                if(mProNode.getSysAddressInfo()== null || mProNode.getSysAddressInfo().getFullAddress()==null)
                {
                    ToastUtil.showShort("暂无地址");
                }

                final String addr = mProNode.getSysAddressInfo().getFullAddress();
                //    设置一个下拉的列表选择项
                builder.setItems(finalstrTypesp, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if("百度地图".equalsIgnoreCase(finalstrTypesp[which]))
                        {
                            MapUtil.openBaiDuNavi(ProFlowDetailActivity.this, 0, 0, addr);
                        }else if("高德地图".equalsIgnoreCase(finalstrTypesp[which]))
                        {
                            MapUtil.openGaoDeNavi(ProFlowDetailActivity.this, 0, 0, addr);
                        }else{
                            MapUtil.openTencentMap(ProFlowDetailActivity.this, 0, 0, addr);
                        }

                    }
                });
                builder.show();
            }
        });


        if (mProNode.getAttachmentList() != null && mProNode.getAttachmentList().size() > 0) {
            mFileList.addAll(mProNode.getAttachmentList());
            mFileAdapter.notifyDataSetChanged();
            findViewById(R.id.area_files).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.area_files).setVisibility(View.GONE);
        }

        if (TextUtils.equals(mProNode.getTimeType().getValue(), "0")) {
            findViewById(R.id.area_time).setVisibility(View.VISIBLE);
            if (mProNode.getStartTime() != 0) {
                tv_flow_time.setText(DateFormatUtils.long2Str(mProNode.getStartTime(), true));
            }
        } else {
            findViewById(R.id.area_time_start).setVisibility(View.VISIBLE);
            findViewById(R.id.area_time_end).setVisibility(View.VISIBLE);
            if (mProNode.getStartTime() != 0) {
                tv_flow_time_start.setText(DateFormatUtils.long2Str(mProNode.getStartTime(), true));
                tv_flow_time_end.setText(DateFormatUtils.long2Str(mProNode.getEndTime(), true));
            }
        }

        if (mProNode.isCountdown()) {
            long gap = -1;
//            tv_flow_countdown.setVisibility();
            if (TextUtils.equals(mProNode.getTimeType().getValue(), "0")) {
                gap = mProNode.getStartTime() - (System.currentTimeMillis() / 1000);
            } else {
                gap = mProNode.getEndTime() - (System.currentTimeMillis() / 1000);
            }
            tv_flow_countdown.setText(ProFlowFragment.formatTimeGap(gap));
        }


        if (canEdit || canDel) {
            titlebar_menu.setVisibility(View.VISIBLE);
            List<String> menus = new ArrayList<>();
            if (canEdit) {
                menus.add("编辑");
            }
            if (canDel) {
                menus.add("删除");
            }

            popupMenu = new CommonPopupMenu(this, menus);
            titlebar_menu.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupMenu.showLocation(R.id.titlebar_menu);// 设置弹出菜单弹出的位置
                    // 设置回调监听，获取点击事件
                    popupMenu.setOnItemClickListener(new CommonPopupMenu.OnItemClickListener() {
                        @Override
                        public void onClick(int index, String str) {
                            if (TextUtils.equals(str, "编辑")) {
                                Intent intent = new Intent(ProFlowDetailActivity.this, CreateProFlowActivity.class);
                                intent.putExtra(CreateProFlowActivity.KEY_ACTION, "edit");
                                intent.putExtra(CreateProFlowActivity.KEY_FLOW, mProNode);
                                startActivity(intent);
                            } else if (TextUtils.equals(str, "删除")) {
                                Dialog tipDialog = new AlertDialog
                                        .Builder(ProFlowDetailActivity.this)
                                        .setTitle("提示")
                                        .setMessage("确认删除当前记录吗？")
                                        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                deleteFlow();
                                            }
                                        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        }).create();
                                tipDialog.setCancelable(false);
                                tipDialog.show();
                            }
                        }
                    });
                }
            });
        }
    }

    private void getDetail() {
        Network
                .getAPIService()
                .getFlowDetail(getUserToken(), mId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        mShapeLoadingDialog.show();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");

                        JsonObject auth = data.getAsJsonObject("auth");
                        canEdit = auth.get("editSchedule").getAsBoolean();
                        canDel = auth.get("deleteSchedule").getAsBoolean();
                        mProNode = ProNodeInfo.parse(data.getAsJsonObject("projectSchedule"));
                        mProNode.setAttachmentList(TaskAtta.parse(data.getAsJsonArray("fileList")));
                        refreshDetail();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }


    private void deleteFlow() {
        Network
                .getAPIService()
                .deleteFlow(getUserToken(), mId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        mShapeLoadingDialog.show();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_FLOW);
                        EventBus.getDefault().post(event);
                        ToastUtil.showShort("节点已删除");
                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }


}

